package com.zhengb.nettydemos.chapter5.delimiter;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by zhengbo on 2019/4/8.
 */
//@Slf4j
public class EchoServerHandler extends ChannelHandlerAdapter {

    private final static Logger logger = LoggerFactory.getLogger(EchoServerHandler.class);

    private final static AtomicInteger counter = new AtomicInteger(0);

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        super.channelReadComplete(ctx);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        String body = (String) msg;

        logger.info("echo server receive request, body:{}, counter is:{}", body, counter.incrementAndGet());
        body += Constants.DELIMITER_STR;
        ByteBuf response = Unpooled.copiedBuffer(body.getBytes());
        ctx.writeAndFlush(response);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.error("echo server handle exception:{}", cause.getMessage());
        ctx.close();
    }
}
